<?php
require_once "../load.php";
error_reporting(0);
$action = $_POST["action"];
unset($_POST["action"]);
if (get_magic_quotes_gpc()) {
    $_POST = Owl_Format::stripslashes_deep($_POST);
}

switch ($action) {
    case 'add_course' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");

        $owl_course = new Owl_Course();
        $max_id =  $owl_course->get_max_id();
        $data["name"] = "Course " . $max_id;
        $data["level"] =$_POST["course_level"];
        $data["unit"] = trim($_POST["course_unit"]);
        
        /* Check course unit string */
        if (preg_match('/[^\d\(\)\-\s]/i', $data["unit"])) {
            $data = array(
                "code" => 0,
                "message" => "<div class=\"ajax-error\">" . __("Invalid course unit") . "</div>"
            );
        }
        else {
            $data["description"] = "Course description " . $max_id;
            $data["nice_url"] = trim("course-" . $max_id);
            if ($owl_course->insert_course($data)) {

                //Language
                $name_lang["id"] = $data["name"];
                $name_lang[$_POST["lang"]] = trim(Owl_Format::esc_html($_POST["course_name"]));
                $description_lang["id"] = $data["description"];
                $description_lang[$_POST["lang"]] = trim(Owl_Format::esc_html($_POST["course_description"]));

                $owl_ulang = new Owl_Ulang();
                $owl_ulang->insert_ulang($name_lang);
                $owl_ulang->insert_ulang($description_lang);

                $data = array(
                    "code" => 1,
                    "message" => "<div class=\"ajax-success\">" . __("Insert course successful!") . "</div>"
                );
            }
            else {
                $data = array(
                    "code" => 0,
                    "message" => "<div class=\"ajax-error\">" . __("Insert course info error: ") . $owl_course->get_error() . "</div>"
                );
            }
        }
        $data = Owl_Functions::json_encode($data);
        echo $data;
        break;
    case 'edit_course' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");
        
        $owl_course = new Owl_Course();
        $old_course = $owl_course->get_course($_POST["nice_url"]);
        $data["level"] = $_POST["course_level"];
        $data["unit"] = $_POST["course_unit"];

        /* Check course unit string */
        if (preg_match('/[^\d\(\)\-\s]/i', $data["unit"])) {
            $data = array(
                "code" => 0,
                "message" => "<div class=\"ajax-error\">" . __("Invalid course unit") . "</div>"
            );
        }
        else {
            if ($owl_course->update_course(trim($_POST["nice_url"]), $data)) {

                //Language
                $name_lang[$_POST["lang"]] = trim(Owl_Format::esc_html($_POST["course_name"]));
                $description_lang[$_POST["lang"]] = trim(Owl_Format::esc_html($_POST["course_description"]));

                $owl_ulang = new Owl_Ulang();
                $owl_ulang->update_ulang($old_course["name"], $name_lang);
                $owl_ulang->update_ulang($old_course["description"], $description_lang);

                $data = array(
                    "code" => 1,
                    "new_nice_url" => $_POST["nice_url"],
                    "message" => "<div class=\"ajax-success\">" . __("Update course successful!") . "</div>"
                );
            }
            else {
                $data = array(
                    "code" => 0,
                    "message" => "<div class=\"ajax-error\">" . __("Update course info error: ") . $owl_course->get_error() . "</div>"
                );
            }
        }
        $data = Owl_Functions::json_encode($data);
        echo $data;
        break;
    case 'delete_course' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");
        
        $owl_course = new Owl_Course();
        $old_course = $owl_course->get_course($_POST["nice_url"]);

        if ($owl_course->delete_course(trim($_POST["nice_url"]))) {

            $owl_ulang = new Owl_Ulang();
            $owl_ulang->delete_ulang($old_course["name"]);
            $owl_ulang->delete_ulang($old_course["description"]);
            
            $data = array(
                "code" => 1,
                "message" => "<div class=\"ajax-success\">" . __("Delete course successful!") . "</div>"
            );
        }
        else {
            $data = array(
                "code" => 0,
                "message" => "<div class=\"ajax-error\">" . __("Delete course info error: ") . $owl_course->get_error() . "</div>"
            );
        }
        $data = Owl_Functions::json_encode($data);
        echo $data;
        break;
    case 'get_course_form' :
        $owl_course = new Owl_Course();
        $course = $owl_course->get_course(trim($_POST["nice_url"]));
        if ($course) {
            echo $owl_course->build_form($course, 0, false);
        }
        else {
            echo "<div class=\"ajax-error\">" . __("Error while fetching course content: ") . $owl_course->get_error() . "</div>";
        }
        break;
    case 'get_course_dropdown' :
        $owl_course = new Owl_Course();
        if (empty($_POST["nice_url"])) {
            echo $owl_course->print_course_dropdown_data('last');
        }
        else {
            echo $owl_course->print_course_dropdown_data($_POST["nice_url"]);
        }
        break;
    case 'get_documents_table' :
        $owl_course = new Owl_Course();
        $course = $owl_course->get_course($_POST['nice_url']);
        echo $owl_course->print_documents_table($course, $_POST['nice_url']);
        break;
    case 'add_document' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        //We will upload the file first
        $file_data = $_FILES["document_link"];
        if ($file_data['error'] == 0 && is_uploaded_file($file_data['tmp_name'])) {
            //Check the type of file and make file name
            $file_info = pathinfo($file_data['name']);
            switch ($file_info['extension']) {
                case 'pdf': $file_type = 'PDF'; break;
                case 'ppt':
                case 'pptx': $file_type = 'PPT'; break;
                case 'doc':
                case 'docx': $file_type = 'DOC'; break;
                default: $file_type = 'Others'; break;
            }
            $file_name = Owl_Format::make_file_name($_POST['document_name']) . "." . $file_info["extension"];
            $aps_path = DOCUMENT_PATH . $_POST["nice_url"] . "/" . strtolower($file_type);
            $rel_path = UPLOAD_DIR . "/" . DOCUMENT_DIR . "/" . $_POST["nice_url"] . "/" . strtolower($file_type);

            //Attempt to create folder if not existed
            if (!file_exists(DOCUMENT_PATH . $_POST["nice_url"])) {
                if (!@mkdir(DOCUMENT_PATH . $_POST["nice_url"], 0755)) {
                    echo '<div class="ajax-error">';
                    echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                    echo sprintf(__("Cannot create folder %s"), UPLOAD_DIR . "/" . DOCUMENT_DIR . "/" . $_POST["nice_url"]);
                    echo '</div>';
                    die();
                }
            }

            if (!file_exists($aps_path)) {
                if (!@mkdir($aps_path, 0755)) {
                    echo '<div class="ajax-error">';
                    echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                    echo sprintf(__("Cannot create folder %s"), $rel_path);
                    echo '</div>';
                    die();
                }
            }

            //Move file to folder
            if (file_exists($aps_path . "/" . $file_name)) {
                echo '<div class="ajax-error">';
                echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                echo __("Document file is duplicate: %s", $file_name);
                echo '</div>';
                die();
            }

            if (!@move_uploaded_file($file_data['tmp_name'], $aps_path . "/" . $file_name)) {
                echo '<div class="ajax-error">';
                echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
                echo sprintf(__("Cannot create file %s in folder %s"),$file_name, $rel_path);
                echo '</div>';
                die();
            }

            //Create new document record
            $owl_course = new Owl_Course();
            if ($owl_course->insert_document($_POST['nice_url'], Owl_Format::encode_xml($_POST['document_name']), $rel_path . "/" . $file_name, $file_type)) {
                echo "<div class=\"ajax-success\">" . __("Upload document successful!") . "</div>";
            }
            else {
                echo '<div class="ajax-error">';
                echo __("Error while uploading file, your data is not affected by this error.");
                echo $owl_course->get_error();
                echo '</div>';
                @unlink($aps_path . "/" . $file_name);
                die();
            }
        }
        else {
            echo '<div class="ajax-error">';
            echo __("Error while uploading file, your data is not affected by this error.") . "<br />";
            echo Owl_Functions::get_upload_error($file_data["error"]);
            echo '</div>';
            die();
        }
        break;
    case 'edit_document' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
        header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
        header("Cache-Control: no-cache, must-revalidate" );
        header("Pragma: no-cache" );
        header("Content-type: text/x-json");

        $old_name = end($_POST["old_name"]);
        $new_name = Owl_Format::encode_xml(end($_POST["document_name"]));
        $nice_url = trim($_POST["nice_url"]);

        $owl_course = new Owl_Course();
        if ($owl_course->update_document_name($nice_url, $old_name, $new_name)) {
            $data = array(
                "code" => 1,
                "message" => "<div class=\"ajax-success\">" . __("Update document successful!") . "</div>"
            );
        }
        else {
            $data = array(
                "code" => 0,
                "message" => "<div class=\"ajax-error\">" . __("Update document info error: ") . $owl_course->get_error() . "</div>"
            );
        }
        $data = Owl_Functions::json_encode($data);
        echo $data;

        break;
    case 'delete_document' :
        $user = Owl_User::get_instance();
        if (!$user->is_logged_in()) {
            die();
        }
        $nice_url = trim($_POST["nice_url"]);
        $owl_course = new Owl_Course();
        foreach ($_POST["old_name"] as $old_name) {
            //Attempt to delete record first
            $old_name = Owl_Format::encode_xml($old_name);
            $old_document = $owl_course->delete_document($nice_url, $old_name);
            if ($old_document == false) {
                echo '<div class="ajax-error">';
                echo __("Error while deleting document, your data is not affected by this error.");
                echo $owl_course->get_error();
                echo '</div>';
                die();
            }

            //Now delete the document file
            $link = $old_document["link"];
            $aps_path = APS_PATH . $link;
            if (!@unlink($aps_path)) {
                echo '<div class="ajax-error">';
                echo __("Error while deleting document, your data is not affected by this error.") . "<br />";
                echo sprintf(__("Cannot delete file %s"), $link);
                echo '</div>';

                //Revert
                $owl_course->insert_document($nice_url, $old_document['name'], $old_document['link'], $old_document['type']);
                die();
            }
        }
        echo "<div class=\"ajax-success\">" . __("Delete documents successful!") . "</div>";
        break;
    case 'input_lang_change' :
        $owl_course = new Owl_Course();
        $translated = $owl_course->get_course_with_lang($_POST["nice_url"], $_POST["lang"]);
        if ($translated == false) {
            $data = array(
                "code" => 0
            );
        }
        else {
            $data = array(
                "code" => 1,
                "name" => $translated[0],
                "description" => $translated[1]
            );
        }
        $data = Owl_Functions::json_encode($data);
        echo $data;
        break;
    default:
        die();
}

die();
